#include "musicListAdapter.h"



musicData::musicData(QObject *parent)
{}


musicListAdapter::musicListAdapter(QObject *parent) : QObject(parent)
{
    len = 0;
    data = NULL;
}


int musicListAdapter::remove(musicData *d)
{
    musicData* tmp;
    musicData* deleData;
    //tmp = data;
    if(len == 0)
    {
        return 0;
    }


    if(data->flag == d->flag)
    {
        deleData = data;
        data = data->next;
        len --;
        delete deleData;
        refreshFlag();
        emit dataChange();
        return 0;
    }

    tmp = data;

    while(tmp->next != NULL)
    {
        if(tmp->next->flag == d->flag)
        {
            deleData = tmp->next;
            tmp->next = tmp->next->next;
            delete deleData;
            len --;
            refreshFlag();
            emit dataChange();
            return 1;
        }
        tmp = tmp->next;
    }
    return 0;
}


int musicListAdapter::append(musicData d)
{
    musicData* tmp = new musicData;
    tmp->name = d.name;
    tmp->path = d.path;
    tmp->handle = NULL;
    tmp->next = data;
    data = tmp;
    len ++;
    refreshFlag();
    emit dataChange();
    return 1;
}

int musicListAdapter::append(QString name, QString path)
{
    musicData* tmp = new musicData;
    tmp->name = name;
    tmp->path = path;
    tmp->handle = NULL;
    tmp->next = data;
    data = tmp;
    len ++;
    refreshFlag();
    emit dataChange();
    return 1;
}


int musicListAdapter::getLen()
{
    return len;
}

musicData* musicListAdapter::getData()
{
    return data;
}


int musicListAdapter::refreshFlag()
{
    musicData* tmp = data;
    int t = 0;
    while(tmp!= NULL)
    {
        tmp->flag = t;
        t ++;
        tmp = tmp->next;
    }
    return 1;
}

int musicListAdapter::musicAddnew(QUrl file)
{
    append(file.fileName().toUtf8().data(),
           file.path().toUtf8().data());
    return 0;
}


musicData* musicListAdapter::getNext(musicData *d)
{
    if(len == 0)
    {
        return NULL;
    }
    if(len == 1)
    {
        return d;
    }

    musicData* tmp = data;
    while(tmp != NULL)
    {
        if(tmp->flag == d->flag)
        {
            if(tmp->next == NULL)
            {
                return data;
            }
            return tmp->next;
        }
        tmp = tmp->next;
    }
}

musicData* musicListAdapter::getPre(musicData *d)
{
    if(len == 0)
    {
        return NULL;
    }
    if(len == 1)
    {
        return d;
    }

    musicData* tmp;
    if(d->flag == data->flag)
    {
        tmp = data;
        while(tmp->next != NULL)
        {
            tmp = tmp->next;
        }
        return tmp;
    }

    //musicData* tmp;
    tmp = data;
    while(tmp->next != NULL)
    {
        if(tmp->next->flag == d->flag)
        {
            return tmp;
        }
        tmp = tmp->next;
    }
}
